<template>
	<view class="oneBtnLogin">
		<view class="upper-container">
			<view class="welcome-login">
				<view class="welcome-text">欢迎登录</view>
				<view class="welcome-img-container">
					<image src="/static/logo_s.png"></image>
				</view>
			</view>
			<view class="slogan">用了帮把关，烦事变简单!</view>
		</view>
		<!-- #ifdef MP -->
		<button class="one-btn-login" :class="[isPass?'':'disabled']"
			:open-type="isPass?'getPhoneNumber|agreePrivacyAuthorization':'btn'" @getphonenumber="getphonenumber"
			@click="getNumbtn">手机号一键登录</button>
		<view style="width: 94%; margin: 30rpx auto 0;">
			<u-button type="primary" plain hover-class="none" shape="circle"
				:customStyle="{backgroundColor:'#ffffff !important'}" @click="back">返回</u-button>
		</view>
		<!-- #endif -->

		<!-- #ifdef APP-PLUS -->
		<button class="one-btn-login" @click="getAppPhoneNumber()">本机号一键登录</button>
		<view style="width: 94%; margin: 30rpx auto 0;">
			<u-button type="primary" plain hover-class="none" shape="circle"
				:customStyle="{backgroundColor:'#ffffff !important'}" @click="back">返回</u-button>
		</view>
		<!-- #endif -->


		<view class="login-message-wrapper">
			<view class="login-message-text">未注册的手机号首次登录将自动注册</view>

			<!-- #ifdef APP-PLUS -->
			<view class="goto-code-text" @click="gotoPage()">验证码登录</view>
			<!-- #endif -->
		</view>
		<view class="consent-agreement">
			<checkbox-group @change="handleCheckboxChange">
				<label>
					<checkbox value="cb" style="transform:scale(0.55)" />
				</label>
				<view>
					阅读并同意
					<text @click="gotoPrivacy('privacy')">《用户隐私协议》</text>
					和
					<text @click="gotoPrivacy('user')">《用户服务协议》</text>
				</view>
			</checkbox-group>
		</view>
		<view class="u-flex-1 h-0 u-flex u-row-center">
			<!-- #ifdef APP-PLUS -->
			<view class="login-type-btn" @click="otherLogin('apple')" v-if="loginProvider.includes('apple')">
				<image src="/static/apple.png" mode="scaleToFill" style="width: 100%;height: 100%;"></image>
			</view>
			<view class="login-type-btn" @click="otherLogin('weixin')" v-if="loginProvider.includes('weixin')">
				<image src="/static/WeChat.png" mode="scaleToFill" style="width: 100%;height: 100%;"></image>
			</view>
			<!-- #endif -->
		</view>

	</view>
</template>

<script>
	import loginBg from '@/static/login-bg.png';
	import common from "@/utils/wxApplet/common.js"
	import config from '@/config.js'
	export default {
		data() {
			return {
				isPass: false,
				loginBg: loginBg,
				loginProvider: [],
				canOneBtn: true,
				push_clientid: '',
				tapBtn: false
			}
		},
		onLoad() {
			// #ifdef MP
			common.wxLogin()
			// #endif
			uni.getProvider({
				service: 'oauth',
				success: (res) => {
					// console.log(res.provider) // ['qq', 'univerify']
					this.loginProvider = res.provider;
					// #ifdef APP
					this.appPreLogin()
					this.getappCLientId()
					// #endif
				}
			});
		},
		onBackPress(option) {
			if (option.from == 'backbutton') {
				this.back()
				return true
			}
		},
		onUnload() {
			// #ifdef MP
			if (!this.tapBtn) {
				uni.$emit('loginBack')
				this.back()
			}
			// #endif
		},
		methods: {
			getappCLientId() {
				uni.getPushClientId({
					success: (res) => {
						console.log('客户端推送标识:', res.cid)
						this.push_clientid = res.cid
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			getNumbtn() {
				if (!this.isPass) {
					this.$u.toast("请阅读并同意协议后再进行登录")
				}
			},
			getphonenumber(e) {
				common.getPhoneNumber(e).then(res => {
					console.log(res);
					if (res) {
						common.getUserInfo()
						uni.navigateBack()
					} else {
						this.$u.toast("您拒绝了授权登录")
					}
				})
			},
			gotoPage() {
				uni.redirectTo({
					url: "/pages/subpage/login/login"
				})
			},
			appPreLogin() {
				let self = this;
				uni.preLogin({
					provider: 'univerify',
					success(res) {
						this.canOneBtn = true
					},
					fail(res) {
						this.canOneBtn = false
					}
				});
			},
			getAppPhoneNumber() {
				let self = this;
				if (this.isPass) {
					uni.login({
						provider: 'univerify',
						univerifyStyle: { // 自定义登录框样式
							//参考`univerifyStyle 数据结构`
							"fullScreen": true, // 是否全屏显示，默认值： false
							"title": '快速登录',
							"backgroundColor": "#ffffff", // 授权页面背景颜色，默认值：#ffffff
							"icon": {
								"path": "static/logo_s.png", // 自定义显示在授权框中的logo，仅支持本地图片 默认显示App logo
								"borderRadius": '50%'
							},
							"phoneNum": {
								"color": "#000000", // 手机号文字颜色 默认值：#000000
								"fontSize": "18" // 手机号字体大小 默认值：18
							},
							"slogan": {
								"color": "#8a8b90", //  slogan 字体颜色 默认值：#8a8b90
								"fontSize": "12" // slogan 字体大小 默认值：12
							},
							// 一键登录
							"authButton": {
								"normalColor": this.$appConfig.mainColor, // 授权按钮正常状态背景颜色 默认值：#3479f5
								"highlightColor": "#599173", // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
								"disabledColor": "#597173", // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）
								"textColor": "#ffffff", // 授权按钮文字颜色 默认值：#ffffff
								"title": "本机号码一键登录" // 授权按钮文案 默认值：“本机号码一键登录”
							},
							// 其他登录方式
							"otherLoginButton": {
								"visible": "true", // 是否显示其他登录按钮，默认值：true
								"normalColor": "#f8f8f8", // 其他登录按钮正常状态背景颜色 默认值：#f8f8f8
								"highlightColor": "#dedede", // 其他登录按钮按下状态背景颜色 默认值：#dedede
								"textColor": "#000000", // 其他登录按钮文字颜色 默认值：#000000
								"title": "验证码登录", // 其他登录方式按钮文字 默认值：“其他登录方式”
								"borderWidth": "1px", // 边框宽度 默认值：1px（仅ios支持）
								"borderColor": "#c5c5c5" //边框颜色 默认值： #c5c5c5（仅ios支持）
							},

							"privacyTerms": {
								"defaultCheckBoxState": "false", // 条款勾选框初始状态 默认值： true
								"textColor": "#8a8b90", // 文字颜色 默认值：#8a8b90
								"termsColor": "#1d4788", //  协议文字颜色 默认值： #1d4788
								"prefix": "我已阅读并同意", // 条款前的文案 默认值：“我已阅读并同意”
								"suffix": "并使用本机号码登录", // 条款后的文案 默认值：“并使用本机号码登录”
								"fontSize": "12", // 字体大小 默认值：12
							}
						},
						success: (res) => {
							console.log(res);
							uniCloud.callFunction({
								name: "getPhoneNumber",
								data: {
									access_token: res.authResult.access_token, // 客户端一键登录接口返回的access_token
									openid: res.authResult.openid // 客户端一键登录接口返回的openid
								}
							}).then((dataRes) => {
								console.log(dataRes);

								this.login(dataRes.result.data.phoneNumber);
							}).catch(err => {
								// this.$u.toast(JSON.stringify(err))
								this.$u.toast('一键登录功能暂不可用，请使用其他登录方式')
								setTimeout(() => {
									uni.closeAuthView();
								}, 1500)
								console.log(err);
							})
						},
						fail: (res) => { // 登录失败
							console.log(res);
							if (res.code == "30002") {
								console.log('其他登录');
								this.gotoPage()
							} else if (res.errCode == "30005") {
								this.$u.toast("登录失败，蜂窝数据网络未打开或sim卡运营商不支持")
							}
							setTimeout(() => {
								uni.closeAuthView();
							}, 1500)
						}
					})
				} else {
					this.$u.toast("请阅读并同意协议后再进行登录")
				}
			},
			login(phone) {
				this.$u.api.oneBtnLogin({
					phone,
					spread_spid: this.$store.state.vuex_SPID,
					cid: this.push_clientid
				}).then(res => {
					this.$u.vuex('vuex_token', 'Bearer ' + res.token);
					this.$u.toast('登录成功')
					common.getUserInfo().then(res => {
						uni.closeAuthView();
						uni.navigateBack()
					})
				})
			},
			otherLogin(type) {
				if (this.isPass) {
					uni.login({
						provider: type,
						success: (res) => {
							console.log(res);
							if (type == 'weixin') {
								const {
									openid,
									unionid
								} = res.authResult
								this.loginSubmit(type, {
									openId: openid,
									unionId: unionid,
								})
							} else {
								uni.getUserInfo({
									provider: 'apple',
									success: (info) => {
										this.loginSubmit(type, {
											openId: info.userInfo.openId
										})
									}
								})
							}
						},
						fail: (err) => {
							this.$u.toast("授权已取消")
							console.log(err);
						}
					})
				} else {
					this.$u.toast("请阅读并同意协议后再进行登录")
				}
			},
			loginSubmit(type, params) {
				this.$u.api.otherLogin(type, {
					...params,
					spread_spid: this.$store.state.vuex_SPID,
					cid: this.push_clientid
				}).then(res => {
					if (res.token) {
						this.$u.toast("登录成功")
						this.$u.vuex('vuex_token', 'Bearer ' + res.token);
						common.getUserInfo().then(res => {
							uni.navigateBack()
						})
					} else {
						this.$u.toast("请绑定手机号")
						this.$u.route({
							url: '/pages/subpage/login/login',
							type: 'redirectTo',
							params: {
								type,
								...params
							}
						})
					}
				})
			},
			handleCheckboxChange(e) {
				let val = e.detail.value;
				this.isPass = val.length > 0;
			},

			gotoPrivacy(type) {
				this.$u.route("/pages/subpage/webview/webview", {
					url: `${config.HTTP_HOST}/yinsi/${type}.html`
				})
			},

			back() {
				this.tapBtn = true;
				const pages = getCurrentPages()
				const prePage = pages[pages.length - 2];
				if (prePage && prePage.route == 'pages/message/index') {
					uni.switchTab({
						url: '/pages/index/index'
					})
				} else {
					uni.navigateBack()
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		width: 100%;
		height: 100%;
		background-color: #fff;
	}

	.oneBtnLogin {
		width: 100%;
		min-height: 100%;
		padding-top: 160rpx;
		padding-bottom: 60rpx;
		// display: flow-root;
		background-repeat: no-repeat;
		background-size: 100% 100%;
		background-image: url('https://bangbaguan.oss-cn-shanghai.aliyuncs.com/APP/login-bg.png');
		display: flex;
		flex-direction: column;

		.upper-container {
			margin-left: 61rpx;

			display: flex;
			flex-direction: column;

			.welcome-login {
				display: flex;
				align-items: center;
				position: relative;

				.welcome-text {
					font-size: 48rpx;
					font-weight: bold;
					color: #000000;
					flex-shrink: 0;
				}

				.welcome-img-container {
					width: 148rpx;
					height: 47rpx;
					margin-left: 25rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}

				&::after {
					content: '';
					position: absolute;
					bottom: -25rpx;
					width: 72rpx;
					height: 5rpx;
					background: $u-type-primary;
					opacity: 0.5;
					border-radius: 3rpx;
				}
			}

			.slogan {
				margin-top: 46rpx;
				font-size: 28rpx;
				font-weight: 400;
				color: #939393;
			}
		}

		.input-wrapper {
			margin-left: 63rpx;
			margin-top: 100rpx;

			.phone-number-wrapper {
				position: relative;
				display: flex;
				align-items: center;
				margin-bottom: 100rpx;

				.icon-container {
					width: 25rpx;
					height: 36rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}

				input {
					margin-left: 26rpx;
					font-size: 30rpx;
					font-weight: 400;
				}

				&::after {
					content: '';
					position: absolute;
					bottom: -32rpx;
					width: 640rpx;
					height: 1rpx;
					background: #d0d0d0;
				}
			}

			.verification-code-wrapper {
				width: 638rpx;
				position: relative;
				display: flex;
				algin-items: center;
				justify-content: space-between;

				.icon-input-wrapper {
					display: flex;
					algin-item: center;

					.icon-container {
						width: 30rpx;
						height: 36rpx;

						image {
							width: 100%;
							height: 100%;
						}
					}

					input {
						margin-left: 22rpx;
						font-size: 30rpx;
						font-weight: 400;
					}
				}

				.get-code {
					right: 0;
					font-size: 28rpx;
					font-weight: 400;
					color: $u-type-primary;
					flex-shrink: 0;
				}

				&::after {
					content: '';
					position: absolute;
					bottom: -32rpx;
					width: 640rpx;
					height: 1rpx;
					background: #d0d0d0;
				}
			}
		}

		.one-btn-login {
			background-color: $u-type-primary;
			color: #ffffff;
			width: 94%;
			margin: 140rpx auto 0 auto;
			height: 88rpx;
			line-height: 88rpx;
			border-radius: 44rpx;
			font-size: 32rpx;

			&.disabled {
				background-color: #cfcfcf;
			}
		}

		.goto-code-text {
			color: $u-type-primary;
			text-align: right;
		}

		.login-message-wrapper {
			margin-left: 32rpx;
			margin-right: 32rpx;
			margin-top: 68rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		.login-message-text {
			font-size: 26rpx;
			font-weight: 400;
			color: #c6c6c9;
		}

		.login-type-btn {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			overflow: hidden;
			margin: 0 100rpx;
		}

		.consent-agreement {
			margin-left: 30rpx;
			margin-top: 40rpx;

			checkbox-group {
				display: flex;
				align-items: center;

				view {
					font-size: 26rpx;
					font-weight: 400;
					color: #c6c6c9;

					text {
						color: $u-type-primary;
					}
				}
			}
		}

		.login-btn {
			margin-left: 62rpx;
			margin-top: 34rpx;
			width: 640rpx;
			height: 88rpx;
			background: $u-type-primary;
			box-shadow: 0rpx 3rpx 7rpx 0rpx rgba(83, 202, 198, 0.25);
			border-radius: 44rpx;
			display: flex;
			justify-content: center;
			align-items: center;

			.login-text {
				font-size: 34rpx;
				font-weight: 400;
				color: #ffffff;
			}
		}

		.quick-login-wrapper {
			margin-top: 75rpx;
			width: 85.5%;
			margin-left: auto;
			margin-right: auto;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.quick-login-text {
				font-size: 26rpx;
				font-weight: 400;
				color: #c6c6c9;
			}

			.left-line,
			.right-line {
				width: 200rpx;
				height: 1rpx;
				background: #d0d0d0;
			}
		}

		.quick-login-btn-wrapper {
			margin-top: 49rpx;
			width: 50%;
			margin-left: auto;
			margin-right: auto;
			display: flex;
			justify-content: center;

			.wechat-wrapper {
				display: flex;
				flex-direction: column;
				align-items: center;

				.img-container {
					width: 60rpx;
					height: 60rpx;

					image {
						height: 100%;
						width: 100%;
					}
				}
			}

			.msg {
				margin-top: 21rpx;
				font-size: 24rpx;
				font-weight: 400;
				color: #c6c6c9;
			}
		}
	}
</style>